MAIN_BASENAME = ocr

all: ps

# Search strings
NEEDINDEX = "Writing index file"
REFERENCES = "(There were undefined references|Rerun to get (cross-references|the bars) right|No file *[aux|toc|lof|lot])"

PDF_FAIL = ($(RM) $(MAIN_BASENAME).aux $(MAIN_BASENAME).pdf && false)

pdf: $(MAIN_BASENAME).pdf

ps: $(MAIN_BASENAME).ps

dvi: $(MAIN_BASENAME).dvi

%.dvi: %.tex
	@echo "### Running LaTeX (1)"
	latex $* </dev/null >/dev/null || $(PDF_FAIL)
	@if (egrep $(REFERENCES) $*.log >/dev/null); then \
		echo "### Running LaTeX to fix references (2)"; \
		latex $* </dev/null >/dev/null || $(PDF_FAIL); \
	fi
	@if (egrep $(NEEDINDEX) $*.log > /dev/null); then \
		echo "### Running makeindex to generate index"; \
		makeindex $* ; \
		echo "### Running LaTeX after generating index"; \
		latex $* </dev/null >/dev/null || $(PDF_FAIL); \
	fi
	@if (egrep $(REFERENCES) $*.log >/dev/null); then \
		echo "### Running LaTeX to fix references (3)"; \
		latex $* </dev/null >/dev/null || $(PDF_FAIL); \
	fi
	@if (egrep $(REFERENCES) $*.log >/dev/null); then \
		echo "### Running LaTeX to fix references (4)"; \
		latex $* </dev/null >/dev/null || $(PDF_FAIL); \
	fi

%.ps: %.dvi
	dvips $< -o $@

%.pdf: %.tex
	@echo "### Running XeLaTeX (1)"
	xelatex $* </dev/null >/dev/null || $(PDF_FAIL)
	@if (egrep $(REFERENCES) $*.log >/dev/null); then \
		echo "### Running XeLaTeX to fix references (2)"; \
		xelatex $* </dev/null >/dev/null || $(PDF_FAIL); \
	fi
	@if (egrep $(NEEDINDEX) $*.log > /dev/null); then \
		echo "### Running makeindex to generate index"; \
		makeindex $* ; \
		echo "### Running XeLaTeX after generating index"; \
		xelatex $* </dev/null >/dev/null || $(PDF_FAIL); \
	fi
	@if (egrep $(REFERENCES) $*.log >/dev/null); then \
		echo "### Running XeLaTeX to fix references (3)"; \
		xelatex $* </dev/null >/dev/null || $(PDF_FAIL); \
	fi
	@if (egrep $(REFERENCES) $*.log >/dev/null); then \
		echo "### Running XeLaTeX to fix references (4)"; \
		xelatex $* </dev/null >/dev/null || $(PDF_FAIL); \
	fi

clean:
	$(RM) *.dvi *.ilg *.ind *.ps *.aux *.idx *.imp *.log *.out *.toc $(MAIN_BASENAME).pdf
